package com.xhlj.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xhlj.entity.Blend;
import com.xhlj.entity.PicUrls;
import com.xhlj.entity.WebhookPayload;
import com.xhlj.service.BlendService;
import com.xhlj.mapper.BlendMapper;
import com.xhlj.utils.RedisKey;
import com.xhlj.utils.Result;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Yzc
 * @description 针对表【blend】的数据库操作Service实现
 * @createDate 2024-03-28 13:37:25
 */
@Service
public class BlendServiceImpl extends ServiceImpl<BlendMapper, Blend>
        implements BlendService {

    private static final String key = "tbOE6PW6ZWwNkSOIydcN3GjAyGIXWv5o";

    @Resource
    private BlendMapper blendMapper;
    @Resource
    private StringRedisTemplate stringRedisTemplate;


    @Override
    public Result blendByMj(PicUrls picUrls) {
        WebClient webClient = WebClient.create();
        Map<String, String> bodys = new HashMap<>();
        bodys.put("image_url1", picUrls.getPicUrlP());
        bodys.put("image_url2", picUrls.getPicUrlS());
        bodys.put("prompt", "The character in the first photo are in the scene of another picture" + " delight  enjoyable" + " --ar " + " 3:4 ");
//      querys.put("timeout", 1000);
//      bodys.put("callback_url", "https://webhook.site/89e53b0f-f3df-4b43-b7bf-3957b52aeee3");
        bodys.put("callback_url", "http://47.99.61.110:9001/mj/receive");

        Mono<Map> mono = webClient.post()
                .uri("https://mjapi.ai-gs.cn/v1/blend?token=" + key)
                .contentType(MediaType.APPLICATION_JSON)
                .body(BodyInserters.fromValue(bodys))
                .retrieve()
                .bodyToMono(Map.class);

        String taskId = (String) mono.block().get("task_id");
        System.out.println("PayController.generateTask   " + taskId);
        String phone = SecurityContextHolder.getContext().getAuthentication().getName();
        stringRedisTemplate.opsForValue().set(RedisKey.GenerateImg_prefix + taskId,  phone);

        return Result.ok(taskId);
    }

    @Override
    public Result receive(WebhookPayload payload) {
        if (payload == null) return null;
        Blend blend = new Blend();
        //TODO:获得当前用户手机号
        String phone = "19519802190";
//      String phone = SecurityContextHolder.getContext().getAuthentication().getName();
        String taskId = payload.getTask_id();
        //TODO:如果出图失败
        if (!payload.isSuccess()) {
                blend.setProgress(-1);
                blend.setUserPhone(phone);
                blend.setTaskId(taskId);
                blendMapper.insert(blend);
                System.out.println("图片生成失败");
                return Result.build(null, 409, "图片生成失败");
        }

        //TODO:如果出图顺利
        //TODO:根据taskId查询数据表看是不是新任务
        LambdaQueryWrapper<Blend> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Blend::getTaskId, taskId);
        Blend blendGet=blendMapper.selectOne(queryWrapper);

        blend.setTaskId(taskId);
        blend.setUserPhone(phone);


        //TODO:若数据库中不存在，说明是新创建的任务,要存入数据库
        if (blendGet== null) {
                if (payload.getProgress() == 100) {
                    blend.setProgress(100);
                    blend.setImgUrl(payload.getRaw_image_url());
                    blendMapper.insert(blend);
                    String rawImageUrl = payload.getRaw_image_url();
                    // 执行下载图片的操作，可以使用Java的网络请求库或其他工具进行下载
                    // 这里只是示例，您需要根据具体情况编写下载图片的逻辑
                    System.out.println("Raw image URL: \n" + rawImageUrl);
                    baseMapper.insert(blend);

                    return Result.ok("ImgUrl:\n" + rawImageUrl);
                } else {
                    blend.setProgress(blend.getProgress());
                    baseMapper.insert(blend);
                    System.out.println("Progress：" + payload.getProgress() + "%");
                    return Result.ok("Progress:\n" + blend.getProgress());
                }
        }
        //TODO:数据库中存在该任务，进行更新
        if (payload.getProgress() != 100) {
            blend.setProgress(blend.getProgress());
            baseMapper.updateById(blend);
            System.out.println("Progress：" + payload.getProgress() + "%");
            return Result.ok("Progress：" + payload.getProgress() + "%");
        }
        else {
            String rawImageUrl = payload.getRaw_image_url();
            blend.setProgress(100);
            blend.setImgUrl(rawImageUrl);
            blendMapper.updateById(blend);

            System.out.println("Raw image URL: \n" + rawImageUrl);
            return Result.ok("ImgUrl:\n" + rawImageUrl);
        }
    }
}





